package edu.ncst.baseweb.service.impl.web;

import cn.wintersun.basecommon.common.Result;
import edu.ncst.baseweb.dao.web.LabDownload;
import edu.ncst.baseweb.mapper.LabDownloadMapper;
import edu.ncst.baseweb.service.intrer.web.LabDownloadService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;


@Service
public class LabDownloadServiceImpl implements LabDownloadService {

    @Autowired
    private LabDownloadMapper LabDownloadMapper;

    private String readPDFAsBase64(String pdfPath) throws IOException {
        Path path = Paths.get(pdfPath);
        byte[] pdfData = Files.readAllBytes(path);
        return Base64.getEncoder().encodeToString(pdfData);
    }

    public Result<List<LabDownload>> list(){
        List<LabDownload> LabDownloadList = LabDownloadMapper.selectList(null);
        for (LabDownload labDownload : LabDownloadList) {
            if (StringUtils.isNotEmpty(labDownload.getDownload())) {
                String pdfPath = "BaseWeb/src/main/java/cn/wintersun/baseweb/StaticResources/File/" + labDownload.getDownload();
                try {
                    String pdfDataBase64 = readPDFAsBase64(pdfPath);
                    System.out.println("PDF read successfully!");
                    labDownload.setDownload(pdfDataBase64); // 假设存在 `setPDF()` 方法设置PDF数据
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("Failed to read PDF!");
                }
            }
        }
        return Result.ok(LabDownloadList);
    }

}
